package handler

import (
	"context"
	"gitee.com/li-yutao0329/pkg"
	"math/rand"
	"time"
	"video_server/basic/config"
	"video_server/basic/model"
	pb "video_server/proto"
)

type Server struct {
	*pb.UnimplementedDemoServer
}

func (s *Server) SendSms(_ context.Context, in *pb.SendSmsReq) (*pb.SendSmsResp, error) {
	ctx := context.Background()
	code := rand.Intn(9000) + 1000
	if !pkg.ValidateMobile(in.Mobile) {
		return &pb.SendSmsResp{
			Message: "手机号码格式不正确",
			Code:    10001,
		}, nil
	}
	err := config.Rdb.Set(ctx, "sendSms"+in.Mobile, code, time.Minute*5).Err()
	if err != nil {
		return &pb.SendSmsResp{
			Message: "验证码发送失败",
			Code:    10002,
		}, nil
	}
	return &pb.SendSmsResp{
		Message: "验证码发送成功",
		Code:    200,
	}, nil
}
func (s *Server) CreateUser(_ context.Context, in *pb.CreateUserReq) (*pb.CreateUserResp, error) {
	ctx := context.Background()
	if !pkg.ValidateMobile(in.Mobile) {
		return &pb.CreateUserResp{
			Message: "手机号码格式不正确",
			Code:    10001,
		}, nil
	}
	get := config.Rdb.Get(ctx, "sendSms"+in.Mobile)
	var user model.User
	err := config.DB.Debug().Where("mobile = ?", in.Mobile).Limit(1).Find(&user).Error
	if err != nil {
		return &pb.CreateUserResp{
			Message: "该用户已注册,请登录",
			Code:    10002,
		}, nil
	}
	if get.Val() != in.SendSmsCode {
		incr := config.Rdb.Incr(ctx, "errors"+in.Mobile).Val()
		if incr > 3 {
			config.Rdb.Del(ctx, get.Val())
			return &pb.CreateUserResp{
				Message: "验证码错误次数过多,请稍后重试",
				Code:    10004,
			}, nil
		}
		return &pb.CreateUserResp{
			Message: "验证码不正确",
			Code:    10003,
		}, nil
	}
	videoName := "video" + time.Now().Format("20060102150405")
	videoNum := time.Now().Format("20060102150405")
	m := model.User{
		Mobile:    in.Mobile,
		VideoName: videoName,
		VideoNum:  videoNum,
	}
	err = config.DB.Debug().Create(&m).Error
	if err != nil {
		return &pb.CreateUserResp{
			Message: "用户注册失败",
			Code:    10005,
		}, nil
	}
	config.Rdb.Del(ctx, get.Val())
	return &pb.CreateUserResp{
		Message: "用户注册成功",
		Code:    200,
	}, nil

}
func (s *Server) LoginUser(_ context.Context, in *pb.LoginUserReq) (*pb.LoginUserResp, error) {
	ctx := context.Background()
	if !pkg.ValidateMobile(in.Mobile) {
		return &pb.LoginUserResp{
			Message: "手机号码格式不正确",
			Code:    10001,
		}, nil
	}
	get := config.Rdb.Get(ctx, "sendSms"+in.Mobile)
	var user model.User
	err := config.DB.Debug().Where("mobile = ?", in.Mobile).Limit(1).Find(&user).Error
	if err != nil {
		return &pb.LoginUserResp{
			Message: "该用户不存在,请注册",
			Code:    10002,
		}, nil
	}
	if get.Val() != in.SendSmsCode {
		incr := config.Rdb.Incr(ctx, "errors"+in.Mobile).Val()
		if incr > 3 {
			config.Rdb.Del(ctx, get.Val())
			return &pb.LoginUserResp{
				Message: "验证码错误次数过多,请稍后重试",
				Code:    10004,
			}, nil
		}
		return &pb.LoginUserResp{
			Message: "验证码不正确",
			Code:    10003,
		}, nil
	}
	config.Rdb.Del(ctx, get.Val())
	return &pb.LoginUserResp{
		Message: "用户登录成功",
		Code:    200,
		Uid:     user.Id,
	}, nil
}
func (s *Server) PersonalHomepage(_ context.Context, in *pb.PersonalHomepageReq) (*pb.PersonalHomepageResp, error) {
	var user model.User
	err := config.DB.Debug().Where("id = ?", in.Uid).Limit(1).Find(&user).Error
	if err != nil {
		return &pb.PersonalHomepageResp{
			Message: "用户未登录",
			Code:    10001,
		}, nil
	}
	var users []model.User
	err = config.DB.Debug().Where("id = ?", in.Uid).Limit(1).Find(&users).Error
	if err != nil {
		return &pb.PersonalHomepageResp{
			Message: "个人信息获取失败",
			Code:    10002,
		}, nil
	}
	var list []*pb.PersonalHomepageList
	for _, m := range users {
		list = append(list, &pb.PersonalHomepageList{
			Mobile:            m.Mobile,
			Name:              m.Name,
			IdCard:            m.IdCard,
			CardStatus:        m.CardStatus,
			VideoName:         m.VideoName,
			VideoNum:          m.VideoNum,
			Image:             m.Image,
			Sex:               m.Sex,
			Age:               m.Age,
			Institution:       m.Institution,
			OrganizationType:  m.OrganizationType,
			AttentionQuantity: m.AttentionQuantity,
			NumberOfFans:      m.NumberOfFans,
			LikeCount:         m.LikeCount,
		})
	}
	return &pb.PersonalHomepageResp{
		Message: "个人信息获取成功",
		Code:    200,
		List:    list,
	}, nil
}
func (s *Server) UserHomepage(_ context.Context, in *pb.UserHomepageReq) (*pb.UserHomepageResp, error) {
	var user model.User
	err := config.DB.Debug().Where("id = ?", in.Uid).Limit(1).Find(&user).Error
	if err != nil {
		return &pb.UserHomepageResp{
			Message: "用户未登录",
			Code:    10001,
		}, nil
	}
	var users []model.User
	err = config.DB.Debug().Where("id = ?", in.ToUserId).Limit(1).Find(&users).Error
	if err != nil {
		return &pb.UserHomepageResp{
			Message: "用户信息获取失败",
			Code:    10002,
		}, nil
	}
	var list []*pb.UserHomepageList
	for _, m := range users {
		list = append(list, &pb.UserHomepageList{
			Mobile:            m.Mobile,
			Name:              m.Name,
			IdCard:            m.IdCard,
			CardStatus:        m.CardStatus,
			VideoName:         m.VideoName,
			VideoNum:          m.VideoNum,
			Image:             m.Image,
			Sex:               m.Sex,
			Age:               m.Age,
			Institution:       m.Institution,
			OrganizationType:  m.OrganizationType,
			AttentionQuantity: m.AttentionQuantity,
			NumberOfFans:      m.NumberOfFans,
			LikeCount:         m.LikeCount,
		})
	}
	return &pb.UserHomepageResp{
		Message: "用户信息信息获取成功",
		Code:    200,
		List:    list,
	}, nil
}
func (s *Server) LikeStatus(_ context.Context, in *pb.LikeStatusReq) (*pb.LikeStatusResp, error) {
	var user model.User
	err := config.DB.Debug().Where("id = ?", in.Uid).Limit(1).Find(&user).Error
	if err != nil {
		return &pb.LikeStatusResp{
			Message: "用户未登录",
			Code:    10001,
		}, nil
	}
	var work model.Work
	err = config.DB.Debug().Where("id = ?", in.WorkId).Limit(1).Find(&work).Error
	if err != nil {
		return &pb.LikeStatusResp{
			Message: "作品不存在",
			Code:    10002,
		}, nil
	}
	like := model.Like{
		UserId: in.Uid,
		WorkId: in.WorkId,
		Status: in.Status,
	}
	err = config.DB.Debug().Updates(&like).Error
	if err != nil {
		return &pb.LikeStatusResp{
			Message: "点赞失败",
			Code:    10001,
		}, nil
	}
	return &pb.LikeStatusResp{
		Message: "点赞成功",
		Code:    200,
	}, nil
}
